#!/bin/sh
if [ -z "$ISOROOT_NAME" ]; then
  echo "You are not in an isoroot!"
  exit
fi

except=$1
if [ -z "$except" ]; then
  echo SWEEPING...
else
  echo SWEEPING except $except
fi

PKGDB=/var/db/pkg
if [ -d "$PKGDB/.snap" ]; then rmdir $PKGDB/.snap; fi
cd $PKGDB
error=0
while true; do
  pkgs=`find $PKGDB -maxdepth 1 -and -mindepth 1 -and -type d | wc -l | awk '{print $1}'`
  if [ ! -z "$except" ]; then
    left=`/usr/bin/grep -Ir $except $PKGDB | wc -l | awk '{print $1}'`
    pkgs=`expr $pkgs - 1`
  else
    left=0
  fi
  if [ $pkgs -le $left ]; then break; fi
  for x in *; do
    if [ ! -d "$x" ]; then continue; fi
    if [ "$x" = "$except" ]; then continue; fi
    if [ -s "$x/+REQUIRED_BY" ]; then continue; fi
    echo "Sweeping $x"
    pkg_delete $x 2>&1 > /dev/null
    error=`expr $error + $?`
  done
done

if [ ! -z "$except" ]; then exit; fi

TMP=/tmp/`basename $0`.$$
MTREE_FILE=`make -f /usr/ports/Mk/bsd.port.mk -V MTREE_FILE`
PREFIX=`make -f /usr/ports/Mk/bsd.port.mk -V PREFIX`
rm -f $PREFIX/share/nls/POSIX $PREFIX/share/nls/en_US.US-ASCII
mtree -U -f $MTREE_FILE -p $PREFIX > $TMP
cd $PREFIX
if [ -d "$PREFIX/.snap" ]; then rmdir $PREFIX/.snap; fi
extra=`grep " extra" $TMP | awk '{print $1}' | grep -v "*.[0-9]"`
if [ ! -z "$extra" ]; then
  echo
  echo EXTRA FILES/DIRECTORIES FOUND
  echo
  error=`expr $error + 1`
  for x in `jot 9 1 9`; do
    MAN=`find $PREFIX -type f | grep "/man/.*\.$x" | sed 's,\.gz,,' | awk -F/ '{print $NF}'`
    if [ ! -z "$MAN" ]; then echo MAN$x= $MAN; fi
  done
  PERL_SUB='/site_perl/s,lib/perl5/site_perl/5.8.8,%%SITE_PERL%%,;s,/mach,/%%PERL_ARCH%%,'
  for e in `cd $PREFIX && find $extra \! -type d | sort`; do echo $e | egrep -v "man/(man|cat)" | sed -e $PERL_SUB ; done
  for e in `cd $PREFIX && find $extra -type d | sort -r`; do echo "@dirrmtry $e" | sed -e $PERL_SUB ; done
  cd $PREFIX && rm -fr $extra
fi
rm $TMP
if [ $error -gt 0 ]; then exit $error; fi
echo DONE
